import axios from 'axios'
import {clearToken, getToken} from "@/utils/token";
import router from "@/router";

// 创建axios实例
const http = axios.create({
    baseURL: 'http://geek.itheima.net/v1_0',
    timeout: 5000
})

http.interceptors.request.use(config => {
    // 添加token请求头
    const token = getToken()
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config;
},error => {
    return Promise.reject(error)
})

http.interceptors.response.use(response => {
    // 过滤数据
    return response.data
},error => {
    console.dir(error)
    if (error.response.status === 401) {
        clearToken()
        router.navigate('/login')
        window.location.reload()
    }

    return Promise.reject(error);
})

export {http}